package com.tanhua.sso.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.tanhua.sso.config.TencentSmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SendSmsUtils {
    @Autowired
    private TencentSmsConfig tencentSmsConfig;

    /**
     * 发送验证码工具类
     *
     * @return String
     */
    public String sendSms(String[] phonenumbers) {
        try {
            String[] params = new String[]{RandomUtils.nextInt(100000, 999999) + "", "2"};
            SmsSingleSender ssender = new SmsSingleSender(this.tencentSmsConfig.getAppid(), this.tencentSmsConfig.getAppkey());
            SmsSingleSenderResult result = ssender.sendWithParam("86", phonenumbers[0],
                    this.tencentSmsConfig.getTemplateId(), params, this.tencentSmsConfig.getSmsSign(), "", "");
            Object errmsg = result.parseToJson(result.getResponse()).get("errmsg");
            if ("OK".equals(errmsg)) {
                System.out.println(result);
                return params[0];
            }
            log.info("发送验证码失败" + result);
        } catch (HTTPException e) {
            // HTTP 响应码错误
            log.error(e.getMessage());
        } catch (JSONException e) {
            // JSON 解析错误
            log.error(e.getMessage());
        } catch (IOException e) {
            // 网络 IO 错误
            log.error(e.getMessage());
        }
        return null;
    }
}
